from pydantic import BaseModel, Field, validator, ConfigDict
from typing import Optional

from pydantic.alias_generators import to_camel


class EmailCodeRequest(BaseModel):
    """邮箱验证码请求"""
    email: str = Field(..., description="邮箱地址")
    type: str = Field(default="register", description="验证码类型：register-注册，reset-重置密码")


class EmailCheckRequest(BaseModel):
    """邮箱检查请求"""
    email: str = Field(..., description="邮箱地址")


class EmailLoginRequest(BaseModel):
    """邮箱检查请求"""
    email: str = Field(..., description="邮箱地址")
    password: str = Field(..., description="密码")

class ResetPasswordRequest(BaseModel):
    """重置密码请求"""
    model_config = ConfigDict(alias_generator=to_camel, from_attributes=True, populate_by_name=True)
    email: str = Field(..., description="邮箱地址")
    verification_code: str = Field(..., description="验证码")
    new_password: str = Field(..., description="新密码")
    confirm_password: str = Field(..., description="确认密码")

    @validator('email')
    def validate_email(cls, v):
        import re
        if not re.match(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', v):
            raise ValueError('邮箱格式不正确')
        return v

    @validator('verification_code')
    def validate_verification_code(cls, v):
        if not v or len(v) != 4 or not v.isdigit():
            raise ValueError('验证码必须是4位数字')
        return v

    @validator('new_password')
    def validate_password(cls, v):
        if len(v) < 6 or len(v) > 20:
            raise ValueError('密码长度必须在6-20位之间')
        if not any(c.isalpha() for c in v) or not any(c.isdigit() for c in v):
            raise ValueError('密码必须包含字母和数字')
        return v

    @validator('confirm_password')
    def validate_confirm_password(cls, v, values):
        if 'new_password' in values and v != values['new_password']:
            raise ValueError('两次输入的密码不一致')
        return v
